/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package mailWS;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

/**
 *
 * @author Abyx
 */
@WebService()
public class MailSendWS {

    /**
     * Web service operation
     */
    @WebMethod(operationName = "sendMail")
    public int sendMail(@WebParam(name = "adr")
    String adr, @WebParam(name = "text")
    String text) {
        // Recipient's email ID needs to be mentioned.
        String to = adr;

        // Sender's email ID needs to be mentioned
        final String username = "test.bgroup.insa@gmail.com";
        final String password = "bgrouptester";
        // Assuming you are sending email from localhost
        //String host = "localhost";

        // Get system properties
        Properties props = new Properties();

        // Setup mail server
        props.setProperty("mail.smtp.auth","true");
        props.setProperty("mail.smtp.starttls.enable","true");
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.port","587");

        // Get the default Session object.
        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        try{
            MimeMessage message = new MimeMessage(session);

            message.setFrom(new InternetAddress(username));
            message.setRecipients(Message.RecipientType.TO,
                                  InternetAddress.parse(to));

            // Set Subject: header field
            message.setSubject("Offre du stade Toulousain");

            // Now set the actual message
            message.setText(text);

            // Send message
            //Transport.send(message);
            System.out.println("Sent message :" + message.toString());
        }catch (MessagingException mex) {
            mex.printStackTrace();
            return -1;
        }
        return 0;
    }

}
